package com.jiyun.service;

import com.jiyun.auth.entity.UserInfo;
import com.jiyun.auth.utils.JwtUtils;
import com.jiyun.client.UserClient;
import com.jiyun.config.JwtProperties;
import com.jiyun.pojo.entity.User;
import com.jiyun.pojo.vo.UserVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class AuthService {

    @Autowired(required = false)
    private UserClient userClient;

    @Autowired(required = false)
    private JwtProperties properties;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    static final String KEY_PREFIX = "user:code:phone:";

    public String authentication(User user1) {

        try {
            // 调用微服务，执行查询
            User user = userClient.queryUser(user1);

            // 如果查询结果为null，则直接返回null
            if (user == null) {
                return null;
            }

            // 如果有查询结果，则生成token
            String token = JwtUtils.generateToken(new UserInfo(user.getUserid(), user.getUsername()),
                    properties.getPrivateKey(), properties.getExpire());
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String shoujidenglu(UserVo userVo) {
        // 校验短信验证码
        String cacheCode = this.redisTemplate.opsForValue().get(KEY_PREFIX + userVo.getPhone());
        if (!StringUtils.equals(userVo.getCode(), cacheCode)) {
            return null;
        }
        try {
            // 调用微服务，执行查询
            User user = this.userClient.queryPhone(userVo);
            // 如果查询结果为null，则直接返回null
            if (user == null) {
                return null;
            }
            // 如果有查询结果，则生成token
            String token = JwtUtils.generateToken(new UserInfo(user.getUserid(), user.getUsername()),
                    properties.getPrivateKey(), properties.getExpire());
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
